<template>
  <div class="bg-light">
    <div class="container-title">
      <span>商品基本信息</span>
    </div>
    <Form ref="formValidate" :model="form" :label-width="100" :rules="ruleValidate">
      <Row class="pr">
        <i-col span="24">
          <FormItem label="商品名称" prop="title">
            <Input v-model="form.title" type="textarea" :maxlength="120" :disabled="isLook" :autosize="{minRows: 1,maxRows: 4}" placeholder="商品名称..." />
          </FormItem>
        </i-col>
      </Row>
      <Row class="pr">
        <i-col span="12" style="height:52px">
          <FormItem label="品牌" prop="brandId">
            <Select v-model="form.brandId" :disabled="isLook || isProduct" @on-change="changeBrand">
              <Option v-for="(item, index) in brandDTOList" :key="index" :value="item.id">{{ item.name }}</Option>
            </Select>
          </FormItem>
        </i-col>
        <i-col v-if="isProduct" span="12">
          <FormItem label="店铺分类">
            <!-- <treeselect
                    v-model="form.ownerCategoryId"
                    :max-height="200"
                    :options="categoryList"
                    :default-expand-level="3"
                    :disabled="isLook"
                    placeholder="请选择店铺分类"/> -->
            <ShopSelect v-model="form.ownerCategoryId" :disabled="isLook" />
          </FormItem>
        </i-col>
        <i-col span="12">
          <FormItem label="单位" prop="unit">
            <Select v-model="form.unit" clearable filterable :disabled="isLook || isProduct">
              <Option v-for="(item, index) in unitArr" :key="index" :value="item.dataValue">{{ item.dataValue }}</Option>
            </Select>
          </FormItem>
        </i-col>
        <i-col span="12">
          <FormItem label="商品编号" prop="code">
            <Input v-model.trim="form.code" :maxlength="30" :disabled="isLook" placeholder="商品编号..." />
          </FormItem>
        </i-col>
        <i-col v-if="productType!=='NORMAL'" span="12" class="require-nature">
          <FormItem label="基础批发价" prop="salePrice">
            <Input v-model.trim="form.salePrice" :disabled="isLook" placeholder="最多2位小数" />
          </FormItem>
        </i-col>
        <i-col v-if="productType!=='NORMAL'" span="12" class="require-nature">
          <FormItem label="建议零售价" prop="marketPrice">
            <Input v-model.trim="form.marketPrice" :disabled="flag||productId?true:false" placeholder="最多2位小数" />
          </FormItem>
        </i-col>
        <i-col v-if="productType!=='NORMAL'" span="12">
          <FormItem label="开票价" prop="invoicePrice">
            <Input v-model.trim="form.invoicePrice" :disabled="isLook" placeholder="最多2位小数" />
          </FormItem>
        </i-col>
        <i-col v-if="productType!=='NORMAL'" span="12">
          <FormItem label="条形码" prop="barcode">
            <Input v-model.trim="form.barcode" :disabled="isLook" placeholder="2-20位数字或字母" />
          </FormItem>
        </i-col>
        <i-col span="12">
          <FormItem label="重量(kg)" prop="weight">
            <Input v-model.trim="form.weight" :disabled="isLook" placeholder="重量..." />
          </FormItem>
        </i-col>
        <i-col span="12">
          <FormItem label="税率" prop="taxRate">
            <Input v-model.trim="form.taxRate" :disabled="isLook" placeholder="税率..." />
            <div class="font-red">如税率是6%，则填0.06</div>
          </FormItem>
        </i-col>
        <i-col v-if="productType!=='NORMAL'" span="12">
          <FormItem label="库存" prop="stock">
            <Input v-model.trim="form.stock" :disabled="isLook" placeholder="库存" />
            <div class="font-red">库存为空则为无限</div>
          </FormItem>
        </i-col>
        <i-col span="12">
          <FormItem label="1手数量" prop="primaryNum">
            <InputNumber v-model="form.primaryNum" :min="1" style="width: 100%" @on-change="onPrimaryNumChange" />
          </FormItem>
        </i-col>
        <i-col span="12">
          <FormItem label="起订数量" prop="orderNum">
            <InputNumber v-model="form.orderNum" :step="form.primaryNum" :min="1" style="width: 100%" />
          </FormItem>
        </i-col>
      </Row>
      <Row v-if="isProduct" class="pr">
        <i-col span="24">
          <FormItem label="商品标语">
            <Input v-model.trim="form.subTitle" type="textarea" :disabled="isLook" :autosize="{minRows: 1,maxRows: 4}" placeholder="商品标语..." />
            <div class="font-red">提示：如同时设置了单品促销宣传语，商品标语将被促销宣传语覆盖！</div>
          </FormItem>
        </i-col>
      </Row>
      <Row v-if="isProduct" class="pr">
        <i-col span="24">
          <FormItem label="标语链接文字">
            <Input v-model.trim="form.subTitleHint" :disabled="isLook" type="textarea" :autosize="{minRows: 1,maxRows: 4}" placeholder="标语链接的文字..." />
          </FormItem>
        </i-col>
      </Row>
      <Row v-if="isProduct" class="pr">
        <i-col span="24">
          <FormItem label="标语链接地址">
            <Input v-model.trim="form.subTitleLink" type="textarea" :disabled="isLook" :autosize="{minRows: 1,maxRows: 4}" placeholder="标语链接的地址..." />
          </FormItem>
        </i-col>
      </Row>
    </Form>
  </div>
</template>
<script>
import ShopSelect from '@/components/ShopSelect'
export default {
  components: {
    ShopSelect
  },
  props: {
    brandDTOList: Array, //商品品牌,
    productId: [Number, String],
    productType: String,
    isLook: {
      type: Boolean,
      default: false
    },
    flag: {
      type: Boolean,
      default: false
    },
    // categoryList: {
    //   type: Array,
    //   default: []
    // },
    isProduct: {
      type: Boolean,
      default: true
    }
  },
  data () {
    const validatePrice = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback(new Error('请输入数字'))
      } else {
        if (!/(^[1-9]\d{0,8}(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(value)) {
          callback(new Error('只能输入九位整数或者两位小数'))
        } else {
          callback()
        }
      }
    }
    const validateCostNumber = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback()
      } else {
        if (!/(^[1-9]\d{0,8}(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(value)) {
          callback(new Error('只能输入九位整数或者两位小数'))
        } else {
          callback()
        }
      }
    }
    const validateBarcode = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback()
      } else {
        if (!/^[A-Za-z0-9]+$/.test(value)) {
          callback(new Error('只能输入数字和英文字符'))
        } else if (value.length < 2 || value.length > 20) {
          callback(new Error('SKU条码的长度在2-20之间'))
        } else {
          callback()
        }
      }
    }
    const validateNumber = (rule, value, callback) => {
      if (value !== '' && value !== null && value !== undefined) {
        if (!/^\d+(\.\d{1,2})?$/.test(value)) {
          callback(new Error('只能输入数字或者小数'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const validateTaxRate = (rule, value, callback) => {
      if (value !== '' && value !== null && value !== undefined) {
        if (!/^0+(\.\d{1,2})?$/.test(value)) {
          callback(new Error('只能输入0-1之间的小数'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const validateCode = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback(new Error('请输入商品编码'))
      } else {
        if (!/^[A-Za-z0-9/\-]+$/.test(value)) {
          callback(new Error('只能输入数字和英文字符以及-/'))
        } else {
          if (value.length < 2 || value.length > 30) {
            callback(new Error('商品编码的长度在2-30之间'))
          } else {
            this.codeIsOnly().then(() => {
              if (this.codeFlag) {
                callback(new Error('该商品编码已存在'))
              } else {
                callback()
              }
            })
          }
        }
      }
    }
    const validateStock = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback()
      } else {
        if (!/^(0|[1-9]\d*)$/.test(value)) {
          callback(new Error('只能输入0或者正整数'))
        } else {
          callback()
        }
      }
    }
    const validateOrderNum = (rule, value, callback) => {
      if (value < this.form.primaryNum) {
        callback(new Error('起订数量必须大于等于1手数量'))
      }
      if (value % this.form.primaryNum !== 0) {
        callback(new Error('起订数量必须是1手数量的倍数'))
      }
      callback()
    }
    return {
      unitArr: [], //存放单位的数组
      form: {
        brandId: null,
        code: '',
        title: '',
        brandName: '',
        taxRate: null,
        unit: '',
        weight: '',
        subTitle: '',
        subTitleHint: '',
        subTitleLink: '',
        skuId: null,
        salePrice: '',
        barcode: '',
        invoicePrice: '',
        marketPrice: '',
        stock: null,
        ownerCategoryId: null,
        primaryNum: 1,
        orderNum: 1
      },
      codeFlag: false,
      ruleValidate: {
        brandId: [
          { required: true, message: '请选择商品品牌', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请填写商品名称', trigger: 'blur' },
          { type: 'string', min: 1, message: '请填写商品名称', trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '请选择单位', trigger: 'change' }
        ],
        taxRate: [
          { validator: validateTaxRate, trigger: 'blur' }
        ],
        weight: [
          { validator: validateNumber, trigger: 'blur' }
        ],
        code: [
          { required: true, validator: validateCode, trigger: 'blur' }
        ],
        barcode: [
          { validator: validateBarcode, trigger: 'blur' }
        ],
        marketPrice: [
          { validator: validatePrice, trigger: 'blur' }
        ],
        salePrice: [
          { validator: validatePrice, trigger: 'blur' }
        ],
        invoicePrice: [
          { validator: validateCostNumber, trigger: 'blur' }
        ],
        stock: [{ validator: validateStock, trigger: 'blur' }],
        orderNum: [{ validator: validateOrderNum, trigger: 'change' }],
        primaryNum: [{ required: true, type: 'number', message: '请填写1手数量', trigger: 'blur' }]
      }
    }
  },
  watch: {
    'form.ownerCategoryId' (newName) {
      if (newName || newName == 0 || newName === '0') {
        this.form.ownerCategoryId = newName
      } else {
        this.form.ownerCategoryId = null
      }
    }
  },
  mounted () {
    this.getUnitData()
  },
  methods: {
    async codeIsOnly () {
      let param = {
        code: this.form.code
      }
      if (this.productId) param.exclusiveId = this.productId ? this.productId : null
      await this.$ajaxGet(`/product/business/code_is_exits`, param).then(data => {
        this.codeFlag = data
      })
    },
    changeBrand (val) {
      this.brandDTOList.forEach(item => {
        if (item.id === val) this.form.brandName = item.name
      })
      this.$emit('onBrandFigure', val) // 品牌改变之后，类目属性里的花纹要清空
    },
    getUnitData () {
      this.$ajaxGet('/product/common/list/UNIT').then(data => {
        this.unitArr = (data || []).map(item => {
          return {
            dataValue: item.dataValue,
            id: item.id
          }
        })
      })
    },
    onPrimaryNumChange () {
      this.$refs.formValidate.validateField('orderNum')
    }
  }
}
</script>
